package com.tiancheng.onecode.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tiancheng.onecode.convert.PlatformConvert;
import com.tiancheng.onecode.entity.Platform;
import com.tiancheng.onecode.exception.Asserts;
import com.tiancheng.onecode.mapper.PlatformMapper;
import com.tiancheng.onecode.model.dto.PayPlatformDTO;
import com.tiancheng.onecode.model.request.admin.PlatformAddReq;
import com.tiancheng.onecode.model.request.admin.PlatformQueryReq;
import com.tiancheng.onecode.model.request.admin.PlatformUpdateReq;
import com.tiancheng.onecode.model.response.PageInfo;
import com.tiancheng.onecode.model.response.admin.PlatformQueryRes;
import com.tiancheng.onecode.service.IPlatformService;
import com.tiancheng.onecode.trade.TradeCache;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author: kellen
 * @Description:平台管理 service impl
 * @Date: create in 2024/12/9 18:22
 */
@Service
public class PlatformServiceImpl extends ServiceImpl<PlatformMapper, Platform> implements IPlatformService {

    @Override
    public PageInfo<PlatformQueryRes> queryPage(PlatformQueryReq params) {
        final LambdaQueryWrapper<Platform> wrapper = new LambdaQueryWrapper<Platform>().eq(StringUtils.isNotEmpty(params.getPlatformCode()), Platform::getPlatformCode, params.getPlatformCode()).like(StringUtils.isNotEmpty(params.getPlatformName()), Platform::getPlatformName, params.getPlatformName());
        final PageInfo<Platform> platformPageInfo = this.baseMapper.find(wrapper, params.getCurrentPage(), params.getPageSize());
        PageInfo<PlatformQueryRes> pageResult = new PageInfo<>(platformPageInfo.getCurrentPage(), platformPageInfo.getPageSize(), platformPageInfo.getTotal());
        if (platformPageInfo.getTotal() > 0) {
            pageResult.setList(PlatformConvert.INSTANCE.convert2PlatformQueryResList(platformPageInfo.getList()));
        }
        return pageResult;
    }

    @Override
    public boolean add(PlatformAddReq params) {
        final long count = this.count(new LambdaQueryWrapper<Platform>().eq(Platform::getPlatformName, params.getPlatformName()));
        Asserts.isTrue(count == 0, "平台已存在");
        // 拼接creatTime时间戳(秒)后进行MD5运算 防止同名
        final Platform platform = PlatformConvert.INSTANCE.convert2Platform(params);
        platform.setCreatedDt(LocalDateTime.now());
        String content = params.getPlatformName() + String.valueOf(platform.getCreatedDt()).substring(0, 19);
        platform.setPlatformCode(DigestUtils.md5DigestAsHex(content.getBytes()).toUpperCase());
        return this.save(platform);
    }

    @Override
    public boolean updatePlatform(PlatformUpdateReq params) {
        final Platform platform = this.getById(params);
        Asserts.isTrue(null != platform, "平台不存在");
        final Platform upDatePlatform = PlatformConvert.INSTANCE.convert2Platform(params);
        upDatePlatform.setId(platform.getId());
        upDatePlatform.setLastUpdDt(LocalDateTime.now());
        return this.updateById(upDatePlatform);
    }

    @Override
    public PlatformQueryRes queryById(Long id) {
        final Platform platform = this.getById(id);
        return PlatformConvert.INSTANCE.convert2PlatformQueryRes(platform);
    }

    @Override
    public PlatformQueryRes queryByPlatformCode(String platformCode) {
        final Platform platform = this.getOne(new LambdaQueryWrapper<Platform>().eq(Platform::getPlatformCode, platformCode));
        return PlatformConvert.INSTANCE.convert2PlatformQueryRes(platform);
    }

    @Override
    public List<PlatformQueryRes> queryByPlatformCodes(Set<String> platformCodes) {
        List<Platform> platforms = this.list(new LambdaQueryWrapper<Platform>().in(Platform::getPlatformCode, platformCodes));
        if(CollectionUtils.isNotEmpty(platforms)){
            return platforms.stream().map(PlatformConvert.INSTANCE::convert2PlatformQueryRes).collect(Collectors.toList());
        }
        return null;
    }

    @Override
    public Platform getOneByPlatformCode(String platformCode) {
        return this.getOne(new LambdaQueryWrapper<Platform>().eq(Platform::getPlatformCode, platformCode));
    }

    /**
     * 鉴于目前用户中台无法支撑多平台，返回默认的一个，以后需要改掉
     *
     * @return
     */
    @Override
    public PayPlatformDTO getDefaultOne(String platformCode) {
        Optional<PayPlatformDTO> treadPlatform = TradeCache.getTreadPlatform(platformCode);
        if (treadPlatform.isPresent()) {
            return treadPlatform.get();
        }
        // TODO 鉴于目前用户中台无法支撑多平台，返回默认的一个，以后需要改掉
        List<Platform> list = null;
        if (StringUtils.isEmpty(platformCode) || platformCode.equals("default")) {
            platformCode = "default";
            list = this.list(new LambdaQueryWrapper<Platform>().isNotNull(Platform::getOrgPaymentChannelId).isNotNull(Platform::getClientId));
        } else {
            list = this.list(new LambdaQueryWrapper<Platform>().eq(Platform::getPlatformCode, platformCode).isNotNull(Platform::getOrgPaymentChannelId).isNotNull(Platform::getClientId));
        }
        Asserts.isTrue(CollectionUtils.isNotEmpty(list), "没有设置默认交易平台信息！");
        if (CollectionUtils.isNotEmpty(list)) {
            PayPlatformDTO payPlatformDTO = new PayPlatformDTO();
            payPlatformDTO.setPlatformCode(list.get(0).getPlatformCode());
            payPlatformDTO.setPlatformName(list.get(0).getPlatformName());
            payPlatformDTO.setPaymentChannelCode(list.get(0).getPaymentChannelCode());
            payPlatformDTO.setOrgPaymentChannelId(list.get(0).getOrgPaymentChannelId());
            payPlatformDTO.setPaymentChannelName(list.get(0).getPaymentChannelName());
            payPlatformDTO.setClientId(list.get(0).getClientId());
            payPlatformDTO.setClientSecret(list.get(0).getClientSecret());
            TradeCache.cacheTreadPlatform(platformCode,payPlatformDTO);
            return payPlatformDTO;
        }
        return null;
    }
}
